import { onBeforeUnmount, watch, computed, shallowRef } from 'vue';
import { resolveUnref } from '@vueuse/core';
import { useMapStore } from '@/store/modules/map';

/**
 * 道路基本信息maker相关，逻辑@/layout/tabs/maps/mapPopUp相关联
 * @param {*} isTool: Ref(boolean) 是否开启了工具
 * @param {*} viewName: 当前页面名称
 * @returns
 */
export function useRoadInfoMarker({ isTool, viewName }) {
  const mapStore = useMapStore();
  const map = computed(() => mapStore.ownMap);
  // 当前点击地图的坐标点 Point | ''
  const clickMarkerPoint = computed(() => mapStore.showPop);

  // 道路基本信息marker对象 BMap.Marker
  const roadInfoMarker = shallowRef(null);
  const onRoadInfoMarkerRemove = () => {
    roadInfoMarker.value.removeEventListener('remove', onRoadInfoMarkerRemove);
    roadInfoMarker.value = null;
  };
  const removeRoadInfoMarker = () => {
    if (roadInfoMarker.value) {
      map.value.removeOverlay(roadInfoMarker.value);
      roadInfoMarker.value = null;
    }
  };
  watch(roadInfoMarker, (val) => {
    if (val) {
      // 需要监听被删除，因为会被外部mapclearOverlays()清除掉
      roadInfoMarker.value.addEventListener('remove', onRoadInfoMarkerRemove);
    }
  });

  /**
   * 地图点击事件函数
   * @param {*} e
   */
  const handleClick = ({ point }) => {
    map.value.centerAndZoom(point, 16);

    if (!roadInfoMarker.value) {
      const myIcon = new window.BMap.Icon('./static/drop.png', new window.BMap.Size(30, 35));
      roadInfoMarker.value = new window.BMap.Marker(point, {
        icon: myIcon,
      });
      map.value.addOverlay(roadInfoMarker.value);
    }

    roadInfoMarker.value.setPosition(point);

    // 显示道路基础信息弹窗
    mapStore.setShowPop(point);
  };

  /**
   * 是否可以监听map的点击事件，用以显示道路基础信息弹窗
   */
  const isListen = computed(() => {
    /**
     * isTool = true，则使用工具，不能监听点击事件, 工具需要和地图交互
     * viewName， 当前页面名称，只有'道路基础'可以点击
     */
    return !resolveUnref(isTool) && ['道路基础'].includes(resolveUnref(viewName));
  });

  watch(
    [isListen, map],
    () => {
      if (!map.value) return;
      map.value.removeEventListener('click', handleClick);
      if (isListen.value) {
        map.value.addEventListener('click', handleClick);
      }
    },
    { immediate: true },
  );

  /**
   * 点击点被清空，则删除marker
   */
  watch(clickMarkerPoint, (val) => {
    if (!val && map.value) {
      removeRoadInfoMarker();
    }
  });

  onBeforeUnmount(() => {
    // 删除marker
    removeRoadInfoMarker();
    // 隐藏地图框
    mapStore.setShowPop('');
    map.value && map.value.removeEventListener('click', handleClick);
  });

  return {
    roadInfoMarker,
    removeRoadInfoMarker,
  };
}
